package com.xdxc.utils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.xdxc.exception.CustomException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CustomDeserializer extends JsonDeserializer<List<Long>> {

    @Override
    public List<Long> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        List<Long> result = new ArrayList<>();

        // 处理数组或字符串格式（兼容性处理）
        if (p.currentToken() == JsonToken.START_ARRAY) {
            while (p.nextToken() != JsonToken.END_ARRAY) {
                addValue(result, p.getText());
            }
        } else if (p.currentToken() == JsonToken.VALUE_STRING) {
            // 如果前端传递的是逗号分隔的字符串（如 "1,2,3"）
            String[] parts = p.getText().split(",");
            for (String part : parts) {
                addValue(result, part.trim());
            }
        }
        return result;
    }

    private void addValue(List<Long> list, String value) {
        try {
            if (value != null && !value.isEmpty()) {
                list.add(Long.parseLong(value));
            }
        } catch (NumberFormatException e) {
            // 抛出带明确信息的异常，方便全局异常处理
            throw new CustomException(400,"错误");
        }
    }
}